package com.sp.ThreadUse;

/**
 * main线程启动两个子线程
 *
 * 继承Thread 和 实现Runnable的区别
 * 1. 从Java的设计来看, 通过继承Thread或者实现Runnable接口来实现线程本质上没有区别, Thread类本身就实现了Runnable接口
 * 2. 实现Runnable接口方式更加适合多个线程共享一个资源, 并且避免了单继承的限制, 建议使用Runnable方式
 */
public class Thread03 {
    public static void main(String[] args) {
        T1 t1 = new T1();
        T2 t2 = new T2();
        Thread thread1 = new Thread(t1);
        Thread thread2 = new Thread(t2);
        thread1.start();
        thread2.start();
    }
}

class T1 implements Runnable {

    int count = 0;

    @Override
    public void run() {
        while (true){
            //每个1秒输出 "hi", 输出5次
            System.out.println("hello, world " + (++count) + " " + Thread.currentThread().getName());
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e){
                e.printStackTrace();
            }
            if (count == 5){
                break;
            }
        }
    }
}

class T2 implements Runnable {

    int count = 0;

    @Override
    public void run() {
        while (true){
            //每个1秒输出 "hi", 输出5次
            System.out.println("hello, world " + (++count) + " " + Thread.currentThread().getName());
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e){
                e.printStackTrace();
            }
            if (count == 5){
                break;
            }
        }
    }
}
